<template>
  <div class="full-height bg-white padding-20 flex column no-wrap">
    <div>
      <div class="title">{{taskName}}任务信息</div>
      <q-form ref="form" greedy>
        <div class="flex margin-t-20 margin-b-20 justify-between">
          <div class="flex items-center">
          <span class="margin-r-8">
            开始时间:
          </span>
            <a-date-picker
                v-model="params.startDate"
                :show-time="{
            format: 'HH:mm'
          }"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
            />
            <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: -3px;font-size: 14px" />
            <q-tooltip max-width="500px">
              这个任务第一次开始执行的时间
            </q-tooltip>
          </span>
          </div>
          <yz-input v-model="params.exeCycle"
                    inputType="select"
                    :options="cycleList"
                    :rules="[0]"
                    title="执行周期"
                    class="margin-r-20 task-add"
          />
          <div class="flex items-center">
          <span class="margin-r-8">
            有效期至:
          </span>
            <a-date-picker
                v-model="params.valiDate"
                :show-time="{
            format: 'HH:mm'
          }"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择有效期至"
            />
            <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: -3px;font-size: 14px" />
            <q-tooltip max-width="500px">
              在这个时间之前，该任务是有效的
            </q-tooltip>
          </span>
          </div>
        </div>
        <div class="flex margin-t-20 margin-b-20 justify-between" v-if="showDriver">
          <div>
            <yz-input v-model="params.driver"
                      inputType="select"
                      :options="driverList"
                      :rules="[0]"
                      title="驱动名称"
                      class="margin-r-20 task-add"
                      :is-disable="isEdit"
            />
          </div>
          <div>
            <yz-input v-model="params.version"
                      inputType="select"
                      :options="versionListAll"
                      :rules="[0]"
                      title="版本号（升级到）"
                      class="margin-r-20 task-add"
            />
          </div>
          <div style="width: 325px"></div>
        </div>
        <div>
          <yz-input v-model="params.remark"
                    :rules="[0]"
                    title="任务说明"
          />
        </div>
      </q-form>
    </div>
    <div class="divider"></div>
    <div>
      <div class="title">网关列表</div>
      <yz-condition-filter
          v-model="params"
          @resetSearch="resetSearch"
          @onSubmit="onSubmit"
          class="filter"
      >
        <fuzzy-search
            v-model.trim="params.gateway"
            :isShowValue="false"
            showAllOption
            isFilter
            smallSize
            filterByFe
            title="网关序列号"
            :options="gatewayOptions"
        ></fuzzy-search>
      </yz-condition-filter>
      <div class="form-inline flex justify-between items-center">
        <q-btn outline color="primary" label="添加网关" @click="addGateway" />
        <div>已选择网关数量：{{tableDataAll.length}}</div>
      </div>
    </div>
    <div class="flex-1 padding-t-10 padding-b-10" style="height: 0">
      <q-table
          :data="tableData"
          :columns="columns"
          row-key="prodId"
          class="scroll stick-last-col full-height"
          :loading="tableLoading"
          :pagination="pagination"
          hide-bottom
          separator="cell"
          no-data-label="暂无数据"
          color="primary"
      >
        <template v-slot:body-cell-deviceCount="props">
          <q-td :props="props">
            <div class="device-count" @click="toDeviceDetail(props.row)">{{props.row.deviceCount}}</div>
          </q-td>
        </template>
        <template v-slot:body-cell-operations="props">
          <q-td class="operations" style="width: 100px">
            <div class="btn-group text-center">
              <q-btn style="font-size: 18px"
                     flat
                     round
                     v-throttle
                     dense
                     color="primary"
                     class="iconfont icontubiao-16"
                     @click="deleteData(props.row)">
                <q-tooltip>删除</q-tooltip>
              </q-btn>
            </div>
          </q-td>
        </template>
      </q-table>
    </div>
    <div class="divider"></div>
    <q-card-actions align="center" class="dialog-footer text-center margin-t-10 form-inline">
      <q-btn outline color="primary" label="取消" @click="hideDialog" class="q-mr-md"/>
      <q-btn unelevated color="primary" label="确认" @click="submit" :loading="submitting"/>
    </q-card-actions>

    <!-- 设备详情 -->
    <DeviceInfos ref="deviceInfos" />

    <!-- 添加网关 -->
    <AddGateway ref="addGateway" @submit="submitGateway" :selectedData="tableDataAll"/>
  </div>
</template>

<script>
import { cycleList, taskTypeObj } from '../components/constant'
import { controllerTypeObj } from '../../components/list-components/gateway-dialog/constant'
import DeviceInfos from '../../components/list-components/device-infos.vue'
import AddGateway from './components/add-gateway.vue'
import { createBoxTask, getTaskDetail, getWaitBoxSize, updateBoxTask } from '../../../../boot/miot/task'
import moment from 'moment'
import { getBindDriverList } from '../../../../boot/miot/plc-list'

export default {
  name: 'add-manage',
  components: {
    DeviceInfos,
    AddGateway
  },
  data () {
    return {
      id: '',
      taskType: '',
      params: {
        startDate: null,
        valiDate: null,
        exeCycle: '1',
        remark: '',
        gateway: '',
        driver: '',
        version: ''
      },
      selectGateway: '',
      submitting: false,
      // 表格分页配置
      pagination: {
        // 总条数
        rowsNumber: 0
      },
      tableLoading: false,
      tableDataAll: [],
      columns: [
        { name: 'prodId', label: '网关序列号', align: 'left', field: 'prodId' },
        { name: 'deviceCount', label: '关联设备', align: 'left', field: 'deviceCount' },
        { name: 'operations', label: '操作', align: 'left', field: 'operations' }
      ],
      driverList: [],
      versionOptions: []
    }
  },
  computed: {
    // 筛选数据
    tableData () {
      if (this.selectGateway) {
        return this.tableDataAll.filter(item => item.prodId === this.selectGateway)
      }
      return this.tableDataAll
    },
    // 网关列表list
    gatewayOptions () {
      return this.tableDataAll.map(item => ({ label: item.prodId, value: item.prodId }))
    },
    // 是否为编辑
    isEdit () {
      return !!this.id
    },
    taskName () {
      if (this.taskType) {
        return taskTypeObj[this.taskType]
      }
      return ''
    },
    showDriver () {
      return this.taskType === '4'
    },
    cycleList () {
      // 如果是驱动升级，只能选单次
      if (this.taskType === '4') {
        return cycleList.filter(item => item.value === '1')
      }
      return cycleList
    },
    driverInfo () {
      const obj = {}
      this.driverList.forEach(item => {
        obj[item.value] = item?.versionList?.map(v => ({
          label: v.version,
          value: v.version
        }))
      })
      return obj
    },
    versionListAll () {
      if (this.params.driver) {
        return this.driverInfo[this.params.driver] || []
      }
      return []
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      const { id, taskType } = vm.$route.query
      vm.id = id
      vm.taskType = taskType
      vm.init()
    })
  },
  methods: {
    init () {
      Object.assign(this.params, this.$options.data.call(this).params)
      this.tableDataAll = []
      if (this.id) {
        this.getDetailData()
      } else {
        this.params.startDate = this.roundTimeWithDate()
      }
      // 如果是升级驱动,获取则获取驱动列表
      if (this.taskType === '4') {
        this.getDriverList()
      }
    },
    // 获取驱动列表
    getDriverList () {
      const params = {
        updateVersion: 2
      }
      getBindDriverList(params).then(res => {
        const resData = res.data
        if (resData) {
          this.driverList = resData.map(item => {
            return {
              label: item.driverName,
              value: item.driverName,
              description: item.description,
              versionList: item.versionList || []
            }
          })
        }
      })
    },
    roundTimeWithDate (dateTimeString) {
      let dateTime = new Date()
      if (dateTimeString) {
        dateTime = new Date(dateTimeString)
      }
      if (isNaN(dateTime)) {
        return 'Invalid datetime format'
      }

      const year = dateTime.getFullYear()
      const month = dateTime.getMonth() + 1 // 月份从 0 开始计数，所以需要加 1
      const day = dateTime.getDate()
      const hours = dateTime.getHours()
      const minutes = dateTime.getMinutes()

      if (minutes <= 30) {
        return `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day} ${hours}:${minutes === 0 ? '00' : '30'}`
      } else {
        const nextHour = (hours + 1) % 24
        return `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day} ${nextHour < 10 ? '0' : ''}${nextHour}:00`
      }
    },
    getDetailData () {
      this.tableLoading = true
      getTaskDetail(this.id, 1).then(res => {
        const data = res.data
        this.params.startDate = moment(data.startDate).format('YYYY-MM-DD HH:mm:ss')
        this.params.valiDate = moment(data.valiDate).format('YYYY-MM-DD HH:mm:ss')
        this.params.remark = data.remark
        this.params.exeCycle = data.exeCycle + ''
        this.params.driver = data.driverName + ''
        this.params.version = data.driverVersion + ''
        data.boxListQueryResVo.forEach(item => {
          item.deviceCount = item.deviceInfo?.length || 0
          item.prodId = item.boxId
        })
        this.tableDataAll = data.boxListQueryResVo
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 重置
    resetSearch () {
      this.params.gateway = ''
    },
    // 查询
    onSubmit () {
      this.selectGateway = this.params.gateway
    },
    // 跳转到设备详情
    toDeviceDetail (row) {
      const deviceInfo = row.deviceInfo || []
      const result = deviceInfo.map((item, index) => {
        return {
          index: index + 1,
          controllerType: controllerTypeObj[item.isPlc],
          driver: item.driverName,
          deviceName: '',
          deviceNum: item.assetNum,
          device: `${item.deviceName}(${item.assetNum})`
        }
      })
      this.$refs.deviceInfos.showDialog(result)
    },
    // 删除选择的数据
    deleteData (row) {
      this.tableDataAll = this.tableDataAll.filter(item => item.prodId !== row.prodId)
    },
    // 添加按钮
    addGateway () {
      // 如果是驱动升级且没选驱动
      if (this.taskType === '4' && !this.params.driver) {
        // 如果没选驱动
        this.$message.warning('请选择驱动')
        return
      }
      this.$refs.addGateway.showDialog(this.taskType, this.params.driver)
    },
    // 提交选择
    submitGateway (selectData) {
      this.tableDataAll = selectData
    },
    // 取消返回
    hideDialog () {
      this.$router.go(-1)
    },
    checkData () {
      let message = ''
      // 校验开始时间
      if (this.params.startDate) {
        const nowTime = new Date().getTime()
        const startTime = new Date(this.params.startDate).getTime()
        if (startTime <= nowTime) {
          message = '开始时间不能早于当前时间'
        }
      } else {
        message = '请输入开始时间'
      }

      if (this.params.startDate && this.params.valiDate) {
        const startTime = new Date(this.params.startDate).getTime()
        const valiDateTime = new Date(this.params.valiDate).getTime()
        if (valiDateTime <= startTime) {
          message = '有效期必须大于开始时间'
        }
      } else {
        message = '请输入有效期'
      }

      if (this.tableDataAll.length === 0) {
        message = '请选择网关'
      }
      return message
    },
    // 提交任务信息
    submit () {
      this.$refs.form.validate(true).then(result => {
        if (result) {
          const message = this.checkData()
          if (message) {
            this.$message.warning(message)
            return
          }
          getWaitBoxSize().then(res => {
            const count = res.data
            let messageTip = ''
            if (count > 0) {
              messageTip = `前面有${count}个网关在执行部署任务，预计等待${Math.ceil(200 * count / 60)}分钟，请确保有效期在此范围`
            } else {
              messageTip = `前面有0个网关在执行部署任务`
            }
            this.$q.dialog({
              title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>${messageTip}</p>`,
              html: true,
              ok: {
                unelevated: true,
                label: '确认'
              },
              cancel: {
                unelevated: true,
                outline: true,
                label: '取消'
              }
            }).onOk(() => {
              this.submitData()
            })
          })
        }
      })
    },

    submitData () {
      const boxIds = this.tableDataAll.map(item => item.boxTableId)
      const data = {
        startDate: moment(this.params.startDate).format('YYYY-MM-DD HH:mm:ss'),
        valiDate: moment(this.params.valiDate).format('YYYY-MM-DD HH:mm:ss'),
        remark: this.params.remark,
        exeCycle: this.params.exeCycle,
        taskType: this.taskType,
        boxIds
      }
      // 如果是升级驱动
      if (this.taskType === '4') {
        data.driverName = this.params.driver
        data.driverVersion = this.params.version
      }
      this.submitting = true
      if (this.isEdit) {
        data.id = this.id
        updateBoxTask(data).then(() => {
          this.$router.go(-1)
        }).finally(() => {
          this.submitting = false
        })
      } else {
        createBoxTask(data).then(() => {
          this.$router.go(-1)
        }).finally(() => {
          this.submitting = false
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.title{
  font-size: 16px;
  color: #5f77fd;
}
.divider{
  width: 100%;
  height: 1px;
  background: #D3D3D3;
  margin: 8px 0
}
.filter{
  margin-top: 10px;
}
/deep/ .form-inline{
  padding: 0;
}
.device-count{
  color: #5f77fd;
  cursor: pointer;
}

.task-add {
  /deep/ .q-field--with-bottom{
    padding-bottom: 0;
  }
}

.margin-r-8{
  margin-right: 8px;
}
</style>
